//
//  JoinViewController.swift
//  onemeetingmac
//
//  Created by 张衡 on 2020/2/26.
//  Copyright © 2020 onemeeting. All rights reserved.
//

import Foundation

struct MBefineData: HandyJSON {
    var isJoin:Bool = true
    var username:String?
    var roomid:String?
    var password:String?
    
    //房间号加密
    var encryption:String?
    
    var ownid:String?
    var number:String?
    var activityId:String?
    var zak:String?
    var hostId:String?
    var token:String?
}


class JoinViewController: NSViewController {
    
    var mData:MBefineData?
    
    override func loadView() {
        let view = NSView.init(frame: NSMakeRect(0, 0, kHomeWinWidth, kHomeWinHeight))
        view.wantsLayer = true
        view.layer?.backgroundColor = NSColor.white.cgColor
        self.view = view
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    convenience init(data:MBefineData?) {
        self.init()
        self.mData = data
        self.setupUI()
        self.loadData()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewWillAppear() {
        super.viewWillAppear()
        //登录状态
        NotificationCenter.default.addObserver(self, selector: #selector(loginStatus(notification:)), name: MTLoginStateNotification, object: nil)
        
        //需要进入会议
        NotificationCenter.default.addObserver(self, selector: #selector(doMeetingNot(not:)), name: MTDoMeetingNotification, object: nil)
    }
    
    func loadData() {
        self.meetingTef.textField.stringValue = self.mData!.roomid ?? "000 000"
        self.meetingTef.textField.isEnabled = self.mData!.isJoin
        
        if self.mData?.username != nil {
            self.nameTef.textField.stringValue = self.mData?.username ?? "壹会通"
        }
        
        let audio = UserInfoManager.shared.onAudio == true ? NSButton.StateValue.on:NSButton.StateValue.off
        self.audioBtn.state = audio
        
        let video = UserInfoManager.shared.onVideo == true ? NSButton.StateValue.on:NSButton.StateValue.off
        self.videoBtn.state = video
    }
    
    func setupUI() {
        self.view.addSubview(contentView)
        contentView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(NSEdgeInsetsMake(40, 30, 20, 30))
        }
        
        //会议号
        self.contentView.addSubview(meetingLab)
        meetingLab.snp.makeConstraints { (make) in
            make.height.equalTo(18)
            make.top.width.centerX.equalToSuperview()
        }
        
        self.contentView.addSubview(meetingTef)
        meetingTef.snp.makeConstraints { (make) in
            make.height.equalTo(32)
            make.width.centerX.equalToSuperview()
            make.top.equalTo(meetingLab.snp.bottom).offset(5)
        }
        
        
        //您的姓名
        self.contentView.addSubview(nameLab)
        nameLab.snp.makeConstraints { (make) in
            make.height.equalTo(18)
            make.width.centerX.equalToSuperview()
            make.top.equalTo(80)
        }
        self.contentView.addSubview(nameTef)
        nameTef.snp.makeConstraints { (make) in
            make.height.equalTo(32)
            make.width.centerX.equalToSuperview()
            make.top.equalTo(nameLab.snp.bottom).offset(5)
        }
        
        self.contentView.addSubview(tipLab)
        tipLab.snp.makeConstraints { (make) in
            make.width.centerX.equalToSuperview()
            make.height.equalTo(18)
            make.top.equalTo(nameTef.snp.bottom).offset(5)
        }
        
        //会议设置
        self.contentView.addSubview(setLab)
        setLab.snp.makeConstraints { (make) in
            make.height.equalTo(18)
            make.width.centerX.equalToSuperview()
            make.top.equalTo(180)
        }
        self.contentView.addSubview(videoBtn)
        videoBtn.snp.makeConstraints { (make) in
            make.height.equalTo(18)
            make.top.equalTo(setLab.snp.bottom).offset(5)
            make.width.equalTo(200)
            make.left.equalToSuperview()
        }
        self.contentView.addSubview(audioBtn)
        audioBtn.snp.makeConstraints { (make) in
            make.height.equalTo(18)
            make.top.equalTo(setLab.snp.bottom).offset(30)
            make.width.equalTo(200)
            make.left.equalToSuperview()
        }
        
        //加入按钮
        self.contentView.addSubview(joinBtn)
        joinBtn.snp.makeConstraints { (make) in
            make.height.equalTo(40)
            make.left.right.bottom.equalToSuperview()
        }
    }
    
    lazy var contentView: NSView = {
        let view = NSView.init()
        return view
    }()
    
    
    lazy var meetingTef: ZHTextField = {
        let view = ZHTextField.init()
        view.textField.placeholderString = "请输入会议号".localized()
        view.style = .number
        view.boardWidth = 0.5
        view.textField.delegate = self
        return view
    }()
    
    lazy var nameTef: ZHTextField = {
        let view = ZHTextField.init()
        view.textField.placeholderString = "请输入您的名字".localized()
        view.boardWidth = 0.5
        view.textField.delegate = self
        return view
    }()
    
    lazy var videoBtn: NSButton = {
        let btn = NSButton.init(frame: NSRect.zero)
        btn.setButtonType(NSButton.ButtonType.switch)
        btn.title = "保持摄像头关闭".localized()
        btn.target = self
        btn.action = #selector(videoBtnAction(senber:))
        return btn
    }()
    
    lazy var audioBtn: NSButton = {
        let btn = NSButton.init(frame: NSRect.zero)
        btn.setButtonType(NSButton.ButtonType.switch)
        btn.title = "不自动连接音频".localized()
        btn.state = NSButton.StateValue.on
        btn.target = self
        btn.action = #selector(audioBtnAction(senber:))
        return btn
    }()
    lazy var joinBtn: ZHButton = {
        let btn = ZHButton()
        btn.font = NSFont.systemFont(ofSize: 14)
        btn.title = "进入会议".localized()
        btn.zh_color = NSColor.white
        btn.zh_backgroundColor = color_main108
        btn.zh_cornerRadius = 3
        btn.hasBorder = true
        btn.target = self
        btn.action = #selector(joinBtnAction(senber:))
        return btn
    }()
    
    lazy var meetingLab: NSTextField = {
        let tef = NSTextField.label(title: "会议号".localized(), textColor: color_gray(160), font: NSFont.systemFont(ofSize: 12))
        return tef
    }()
    
    lazy var nameLab: NSTextField = {
        let tef = NSTextField.label(title: "您的姓名".localized(), textColor: color_gray(160), font: NSFont.systemFont(ofSize: 12))
        return tef
    }()
    
    lazy var tipLab: NSTextField = {
        let tef = NSTextField.label(title: "(仅支持汉字，字母，数字，16字符以内)".localized(), textColor: color_gray(160), font: NSFont.systemFont(ofSize: 10))
        return tef
    }()
    
    
    lazy var setLab: NSTextField = {
        let tef = NSTextField.label(title: "会议设置".localized(), textColor: color_gray(160), font: NSFont.systemFont(ofSize: 12))
        return tef
    }()
    
    @objc func joinBtnAction(senber:ZHButton) {
        let txt = self.nameTef.textField.stringValue
        if txt == "" {
            show_msg("请输入有效的名称".localized())
            return
        }else if String.validatedNickName(nickNameStr: txt) != true {
            self.tipLab.textColor = NSColor.red
            return
        }
        
        let joinId = self.meetingTef.textField.stringValue.clearId()
        if joinId != "" {
            self.reLoadMeeting(joinId: joinId)
            
            if let ownid = UserInfoManager.shared.ownid {
                NetEngine.reponseName(txt, id:ownid, success: nil)
            }
        }
        
    }
}

extension JoinViewController:NSTextFieldDelegate {
    
    func controlTextDidBeginEditing(_ obj: Notification) {
        let view = obj.object as? NSTextField
        let textField  = view?.superview as? ZHTextField
        if textField == nameTef {
            self.nameTef.boardColor = color_main108
        }
        if textField == meetingTef {
            self.tipLab.textColor = color_gray(160)
            self.meetingTef.boardColor = color_main108
        }
    }
    
    func controlTextDidEndEditing(_ obj: Notification) {
        let view = obj.object as? NSTextField
        let textField = view?.superview as? ZHTextField
        if (textField != nil) {
            if textField!.style == .number {
                textField!.textField.stringValue = textField!.textField.stringValue
            }
        }
        
        
        if textField == nameTef {
            self.nameTef.boardColor = color_gray(200)
        }
        if textField == meetingTef {
            self.meetingTef.boardColor = color_gray(200)
        }
    }
    
    
    @objc func videoBtnAction(senber:NSButton) {
        let isok = senber.state==NSButton.StateValue.on ? true:false
        UserInfoManager.shared.onVideo = isok
    }
    
    @objc func audioBtnAction(senber:NSButton) {
        let isok = senber.state==NSButton.StateValue.on ? true:false
        UserInfoManager.shared.onAudio = isok
    }
    
}


extension JoinViewController {
    
    //获取进入会议数据
    func reLoadMeeting(joinId:String)  {
        let number = self.meetingTef.textField.stringValue
        let name = self.nameTef.textField.stringValue
        let pwd = self.mData?.password
        
        let num = (self.mData?.encryption != nil) ? (self.mData?.roomid ?? ""):number
        
        guard var clearData = self.mData else {
            return
        }
        clearData.number = num.clearId()
        clearData.username = name
        clearData.password = pwd
        guard let parms = clearData.toJSON() else {
            return
        }
        
        UserInfoManager.shared.roomId = num
        
        if self.mData?.isJoin == true {
            RtcEngine.responseDataJoinAndDoAndHost(parmas: parms, success: nil)
        }else {
            RtcEngine.responseDataHostAndDo(parmas: parms, success: nil)
        }
        
        
    }
}


extension JoinViewController {
    @objc func doMeetingNot(not:Notification) {
        guard let mData = not.object as? MBefineData else {
            return
        }
        self.mData = mData
        self.loadData()
    }
    
    @objc func loginStatus(notification:Notification) {
        if self.mData?.isJoin == false{
            self.meetingTef.textField.stringValue = self.mData?.roomid!.stringToPhone() ?? "000 000"
            self.nameTef.textField.stringValue = self.mData?.username ?? ""
            show_msg("数据已刷新".localized())
        }
    }
}
